package com.ruirenyun.util.ocr;

import com.baidu.aip.ocr.AipOcr;
import com.ruirenyun.entity.constant.SYS;
import com.ruirenyun.util.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class OcrUtil {
    private static OcrConfig ocrConfig;

    public static void setOcrConfig(OcrConfig config) {
        ocrConfig = config;
    }

    /**
     * 获取身份证信息
     *
     * @return
     */
    public static OcrRespVo getIDCard(MultipartFile file) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(ocrConfig.getAppid(), ocrConfig.getAppKey(), ocrConfig.getSecretkey());

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        String idCardSide = "front";

        // 参数为本地路径
        JSONObject res = null;
        try {
            res = client.idcard(file.getBytes(), idCardSide, options);
        } catch (IOException e) {
            log.error("识别出错", e);
            throw new CommonException(SYS.SUP10005.name());
        }
        JSONObject wordsResult = res.getJSONObject("words_result");

        Map<String, String> keyMap = new HashMap<>();
        keyMap.put("姓名", "name");
        keyMap.put("民族", "nation");
        keyMap.put("住址", "detailed_address");
        keyMap.put("公民身份号码", "ID_number");
        keyMap.put("出生", "birthday");
        keyMap.put("性别", "sex");

        Map map = new HashMap<>();
        for (String str : wordsResult.keySet()) {
            JSONObject ws = (JSONObject) wordsResult.get(str);
            String key = keyMap.get(str);
            map.put(key, ws.get("words"));
            //生日日期格式转换
            if ("birthday".equals(key)) {

                String birthday = dateToStr(StrToDate(String.valueOf(ws.get("words")), "yyyyMMdd"), "yyyy-MM-dd");
                map.put(key, birthday);
            }
        }
        return new OcrRespVo((String) map.get("name"), (String) map.get("ID_number"));
    }

    /**
     * 获取银行卡信息
     *
     * @return
     */
    public static Map getBankCard(String imageUrl) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(ocrConfig.getAppid(), ocrConfig.getAppKey(), ocrConfig.getSecretkey());
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        // 参数为本地路径
        JSONObject res = client.bankcard(imageUrl, options);

        JSONObject wordsResult = res.getJSONObject("result");
        return wordsResult.toMap();
    }

    /**
     * 通用识图
     *
     * @return
     */
    public static Map commonOcr(String imageUrl) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(ocrConfig.getAppid(), ocrConfig.getAppKey(), ocrConfig.getSecretkey());
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        //调用接口
        JSONObject res = client.basicGeneral(imageUrl, new HashMap<>());
        return res.toMap();
    }

    /**
     * 日期转换成字符串
     *
     * @param d
     * @param format
     * @return str
     */
    public static String dateToStr(Date d, String format) {
        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        //设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(d);
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str, String format) {

        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
}
